package com.sl.u_push_plugin

import android.R.array
import android.content.Context
import android.util.Log
import com.umeng.commonsdk.UMConfigure
import com.umeng.message.IUmengCallback
import com.umeng.message.IUmengRegisterCallback
import com.umeng.message.PushAgent
import com.umeng.message.UTrack
import com.umeng.message.entity.UMessage
import com.umeng.message.tag.TagManager.TCallBack
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodChannel
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable


class PushManager private constructor() {

    private var context: Context? = null
    private var deviceToken: String? = null
    var events: EventChannel.EventSink? = null
    val pushInstance by lazy {
        PushAgent.getInstance(context)
    }

    fun initEvents(events: EventChannel.EventSink?) {
        this.events = events
    }


    companion object {
        val instance by lazy {
            PushManager()
        }
    }

    fun initContext(context: Context?) {
        this.context = context
    }

    fun pushRegister() {
        pushInstance.register(object : IUmengRegisterCallback {
            override fun onSuccess(p0: String?) {
                Log.e(Tag.SLUPushError, "注册成功：deviceToken：-------->  " + p0);
                deviceToken = p0;
//                initUMengMessagePushService()
//                result.success(mapOf("resCode" to 0, "resValue" to p0))
//                Observable.just(p0).observeOn(AndroidSchedulers.mainThread()).subscribe {
//                    result.success(mapOf("resCode" to 0, "resValue" to p0))
//                }
            }

            override fun onFailure(p0: String?, p1: String?) {
                Log.e(Tag.SLUPushError, "注册失败：deviceToken：-------->  " + "s:" + p0 + ",s1:" + p1)
//                Observable.just(mapOf("value" to p0, "reason" to p1)).observeOn(AndroidSchedulers.mainThread()).subscribe {
//                    result.success(mapOf("resCode" to -1, "resValue" to "error : $p0 , reason :$p1"))
//                }
            }
        })
    }

    fun appStart(context: Context) {
        PushAgent.getInstance(context).onAppStart();
    }

    fun initUPush(context: Context, appKey: String, appSecretKey: String) {
        UMConfigure.init(context, appKey, "Umeng", UMConfigure.DEVICE_TYPE_PHONE, appSecretKey);
        UMConfigure.setLogEnabled(true)

        PushAgent.getInstance(context).register(object : IUmengRegisterCallback {
            override fun onSuccess(p0: String?) {
                if (events == null) {
                    Log.e(Tag.SLUPushError, "flutter 未完成 注册，无法发送消息，请使用get方法获取")
                }

                deviceToken = p0
                var result = ResaultData().Builder().initData("code", 1).initData("value", p0
                        ?: "").initType(TypeData.login).build()
                events?.run {
                    success(result)
                }
            }

            override fun onFailure(p0: String?, p1: String?) {
                Log.e(Tag.SLUPushError, "注册失败：s:$p0,s1:$p1")
                var result = ResaultData().Builder().initData("code", -1).initData("value", "code:$p0,error:$p1").initType(TypeData.login).build()
                events?.run {
                    success(result)
                }
            }
        })
        PushAgent.getInstance(context).onAppStart()
//        val notificationClickHandler: UmengNotificationClickHandler = object : UmengNotificationClickHandler() {
//            override fun launchApp(context: Context, msg: UMessage) {
//                super.launchApp(context, msg)
//                sendClickData(msg)
//            }
//
//            override fun openUrl(context: Context, msg: UMessage) {
//                super.openUrl(context, msg)
//                sendClickData(msg)
//            }
//
//            override fun openActivity(context: Context, msg: UMessage) {
//                super.openActivity(context, msg)
//                sendClickData(msg)
//            }
//
//            override fun dealWithCustomAction(context: Context, msg: UMessage) {
//                Toast.makeText(context, msg.custom, Toast.LENGTH_LONG).show()
//            }
//        }
//        PushAgent.getInstance(context).notificationClickHandler = notificationClickHandler
    }

    private fun sendClickData(uMessage: UMessage) {
        var result = ResaultData().Builder()
        uMessage.extra?.forEach {
            result.initData(it.key, it.value)
        }
        result.initType(TypeData.message);
        events?.success(result.build())
    }

    ///应用前台是否显示通知
    fun changeShowNotificaitonOnForeground(show: Boolean) {
        pushInstance.setNotificaitonOnForeground(show)
    }

    fun setNoDisturbMode(startHour: Int, endHour: Int, startMin: Int, endMin: Int) {
        pushInstance.setNoDisturbMode(startHour, startMin, endHour, endMin)
    }

    fun initUMengMessagePushService() {
        pushInstance.setPushIntentServiceClass(UMessagePushService::class.java)
    }

    fun getPushDeviceToken(): String {
        return deviceToken ?: ""
    }

    fun openPush(result: MethodChannel.Result) {
        pushInstance.enable(object : IUmengCallback {
            override fun onSuccess() {
                Observable.just(1).observeOn(AndroidSchedulers.mainThread()).subscribe {
                    result.success(mapOf("data" to mapOf("success" to true, "message" to "")))
                }
            }

            override fun onFailure(p0: String?, p1: String?) {
                Observable.just(1).observeOn(AndroidSchedulers.mainThread()).subscribe {
                    result.success(mapOf("data" to mapOf("success" to false, "message" to p0 + p1)))
                }
            }
        })
    }

    fun closePush(result: MethodChannel.Result) {
        pushInstance.disable(object : IUmengCallback {
            override fun onSuccess() {
                Observable.just(1).observeOn(AndroidSchedulers.mainThread()).subscribe {
                    result.success(mapOf("data" to mapOf("success" to true, "message" to "")))
                }
            }

            override fun onFailure(p0: String?, p1: String?) {
                Observable.just(1).observeOn(AndroidSchedulers.mainThread()).subscribe {
                    result.success(mapOf("data" to mapOf("success" to false, "message" to p0 + p1)))
                }
            }
        })
    }

    fun addTags(array: List<String>, result: MethodChannel.Result) {
        val tags = array.toTypedArray()
        pushInstance.tagManager.addTags(TCallBack { isSuccess, ITagManager_result ->
            Observable.just(isSuccess).observeOn(AndroidSchedulers.mainThread()).subscribe {
                result.success(mapOf("data" to mapOf("success" to isSuccess, "message" to ITagManager_result.msg, "remain" to ITagManager_result.remain)))
            }
        }, *tags)

    }

    fun deleteTags(array: List<String>, result: MethodChannel.Result) {
        val tags = array.toTypedArray()
        pushInstance.tagManager.deleteTags(TCallBack { isSuccess, ITagManager_result ->
            Observable.just(isSuccess).observeOn(AndroidSchedulers.mainThread()).subscribe {
                result.success(mapOf("data" to mapOf("success" to isSuccess, "message" to ITagManager_result.msg, "remain" to ITagManager_result.remain)))
            }

        }, *tags)
    }

    fun getTags(result: MethodChannel.Result) {
        pushInstance.tagManager.getTags { b, mutableList ->
            Observable.just(b).observeOn(AndroidSchedulers.mainThread()).filter {
                b
            }.subscribe {
                result.success(mapOf("data" to mapOf("tags" to mutableList)))
            }

        }
    }

    fun addAlias(alias: String, type: String, result: MethodChannel.Result) {
        pushInstance.addAlias(alias, type) { isSuccess, message ->
            Observable.just(isSuccess).observeOn(AndroidSchedulers.mainThread()).subscribe {
                result.success(mapOf("data" to mapOf("success" to isSuccess, "message" to message)))
            }
        }
    }

    fun setAlias(alias: String, type: String, result: MethodChannel.Result) {
        pushInstance.setAlias(alias, type) { isSuccess, message ->
            Observable.just(isSuccess).observeOn(AndroidSchedulers.mainThread()).subscribe {
                result.success(mapOf("data" to mapOf("success" to isSuccess, "message" to message)))
            }
        }
    }

    fun deleteAlias(alias: String, type: String, result: MethodChannel.Result) {
        pushInstance.deleteAlias(alias, type) { isSuccess, message ->
            Observable.just(isSuccess).observeOn(AndroidSchedulers.mainThread()).subscribe {
                result.success(mapOf("data" to mapOf("success" to isSuccess, "message" to message)))
            }
        }
    }

    fun setLogEnable(isLog:Boolean){
        UMConfigure.setLogEnabled(isLog)
    }

}